package sojupay

import (
	"context"
	"errors"
	"fmt"
	"strconv"
	"time"

	"gitee.com/liuxuezhan/ar-platform/admin-api/internal/pay/base"
	"github.com/bytedance/sonic/decoder"
)

type Factory struct {
}

func (p *Factory) CreatePay(config base.Config) base.Payment {
	return &Sojupay{
		Url:        config.Url,
		MerchantId: config.MerchantId,
		SecretKey:  config.SecretKey,
		NotifyUrl:  config.NotifyUrl,
	}
}

type Sojupay struct {
	MerchantId string
	SecretKey  string
	Url        string
	NotifyUrl  string
}

type Resp struct {
	Code string `json:"error_code"`
	Msg  string `json:"error_msg"`
	Data any    `json:"data"`
}

// Withdraw 代付订单创建
func (p *Sojupay) Withdraw(ctx context.Context, req map[string]any) (resp base.WithdrawRes, err error) {
	// 请求第三方接口
	url := p.Url + "/gateway/api/v2/payouts"
	params := make(map[string]any)
	params["platform_id"] = p.MerchantId
	params["service_id"] = "SVC0004"
	params["payout_cl_id"] = req["Order"].(map[string]any)["OrderNo"]
	params["amount"] = fmt.Sprintf("%.0f", req["Order"].(map[string]any)["RealAmount"].(float64)*100)
	params["notify_url"] = p.NotifyUrl
	params["bank_name"] = req["Order"].(map[string]any)["UserBank"].(map[string]any)["IfscCode"]
	params["name"] = req["Order"].(map[string]any)["UserBank"].(map[string]any)["UserName"]
	params["number"] = req["Order"].(map[string]any)["UserBank"].(map[string]any)["CardNumber"]
	params["request_time"] = strconv.FormatInt(time.Now().Unix(), 10)
	params["sign"] = GenerateSign(params, p.SecretKey)
	result, err := sendRequest(ctx, url, params, "post")
	if err != nil {
		return
	}
	resp = base.WithdrawRes{
		OrderSn:      req["Order"].(map[string]any)["OrderNo"].(string),
		ThirdOrderSn: result.Data.(map[string]any)["payout_id"].(string),
	}
	return
}

// 发送请求
func sendRequest(ctx context.Context, url string, params map[string]any, method string) (resp Resp, err error) {
	output, err := base.SendJson(ctx, url, params, method)
	if err != nil {
		return resp, err
	}
	dc := decoder.NewDecoder(output)
	dc.UseNumber()
	dc.Decode(&resp)
	if resp.Code != "0000" {
		return resp, errors.New(resp.Msg)
	}
	return
}
